<template>
  <!-- 放置弹出层组件 -->
  <el-dialog :title="showTitle" :visible="showDialog" @close="btnCancel">
    <!-- 表单数据 -->
    <el-form
      ref="deptForm"
      label-width="120px"
      :model="formData"
      :rules="rules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getEmployeesSimples"
        >
          <el-option
            v-for="item in people"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        ></el-input>
      </el-form-item>
    </el-form>
    <!-- 确定和取消 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="btnCancel">取消</el-button>
        <el-button size="small" type="primary" @click="btnOk">确认</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getEmployeesSimples } from '@/api/employees'
import { getDepartments, addDepartments, getDepartmentDetail, updateDepartmentDetail } from '@/api/departments'
export default {

  props: {
    showDialog: {
      type: Boolean,
      default: false
    },

    treeNode: {
      type: Object,
      default: null
    }
  },

  data () {
    const checkNameRepeat = async (rule, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.formData.id) {
        // 编辑模式同级名字不能重复
        isRepeat = depts.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id).some(item => item.name === value)
      } else {
        isRepeat = depts.filter(item => item.pid === this.treeNode.id).some(item => item.name === value)
      }

      // 如果isRepeat为true，表示找到了一样的名字
      isRepeat ? callback(new Error(`同级部门下已经存在这个${value}部门了`)) : callback()
    }

    const checkCodeRepeat = async (rule, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.formData.id) {
        // 编辑模式  因为编辑模式下 不能算自己
        isRepeat = depts.some(item => item.id !== this.formData.id && item.code === value && value)
      } else {
        // 新增模式
        isRepeat = depts.some(item => item.code === value && value) // 这里加一个 value不为空 因为我们的部门有可能没有code
      }

      isRepeat ? callback(new Error(`组织架构中已经有部门使用${value}编码`)) : callback()
    }

    return {
      // 表单数据
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: checkNameRepeat, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: checkCodeRepeat, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍长度在 1 到 300 个字符', trigger: 'blur' }
        ]
      },
      people: ''
    }
  },
  computed: {
    showTitle () {
      return this.formData.id ? '编辑部门' : '新增子部门'
    }
  },

  methods: {
    // 获取详情方法
    async getDepartmentDetail (id) {
      this.formData = await getDepartmentDetail(id)// props传值是异步的
    },

    async getEmployeesSimples () {
      const res = await getEmployeesSimples()
      this.people = res
    },

    // 表单提交
    async btnOk () {
      try {
        await this.$refs.deptForm.validate()
        if (this.formData.id) {
          await updateDepartmentDetail(this.formData)
          this.$message.success('修改部门信息成功')
        } else {
          await addDepartments({ ...this.formData, pid: this.treeNode.id })
          this.$message.success('添加部门成功')
        }

        this.$emit('addDepts') // 告诉父组件 新增数据成功 重新拉取数据
        this.$emit('update:showDialog', false)
      } catch (error) {
        this.$message.error('添加/修改部门失败')
      }
    },

    btnCancel () {
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }

      this.$refs.deptForm.resetFields() // 重置校验字段

      this.$emit('update:showDialog', false) // 关闭
    }
  }
}
</script>

<style>
</style>
